﻿using Kingdee.BOS;
using Kingdee.BOS.App.Data;
using Kingdee.BOS.Contracts;
using Kingdee.BOS.Core.Log;
using Kingdee.BOS.Core.Report;
using Kingdee.BOS.Model.ReportFilter;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.ServiceHelper;
using Kingdee.BOS.Util;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Text;

namespace RCE.K3.YGJD.Service.PlugIn.Schedule
{
    [HotUpdate]
    [Description("应收款余额表 保存")]
    public class SaveReceivableBalanceSchedule : IScheduleService
    {
        public void Run(Context ctx, Kingdee.BOS.Core.Schedule schedule)
        {
            string reportFormId = "AR_SumReport";
            string filterFormId = "AR_SumRepFilter";
            Dictionary<string, string> dicFilter = new Dictionary<string, string>();
            dicFilter.Add("SettleOrgLst", "1");
            dicFilter.Add("BeginDate", DateTime.Now.ToString("yyyy-MM-dd"));
            dicFilter.Add("EndDate", DateTime.Now.ToString("yyyy-MM-dd"));
            dicFilter.Add("FUSEDATE", "1");
            dicFilter.Add("FDateRadioGrp", "1");
            dicFilter.Add("FSTARTYEAR", DateTime.Now.Year.ToString());
            dicFilter.Add("FENDYEAR", DateTime.Now.Year.ToString());
            dicFilter.Add("FSTARTPERIOD", DateTime.Now.Month.ToString());
            dicFilter.Add("FENDPERIOD", DateTime.Now.Month.ToString());
            string filterSchemeSql = $"/*dialect*/SELECT FSCHEMEID FROM T_BAS_FILTERSCHEME where FFORMID = '{filterFormId}' and FSCHEMENAME = 'Default Scheme'";
            DynamicObjectCollection filterSchemeCollection = DBUtils.ExecuteDynamicObject(ctx, filterSchemeSql);
            string schemeId = "";
            if (filterSchemeCollection.Count > 0)
            {
                schemeId = filterSchemeCollection[0]["FSCHEMEID"].ToString();
            }
            DataTable dt = GetReportData(ctx, reportFormId, filterFormId, dicFilter, schemeId);

            foreach (DataRow item in dt.Rows)
            {
                try
                {
                    string updSql = $"update T_BD_CUSTOMER set F_UIXC_ReBalance = {Convert.ToDecimal(item["FLEFTAMOUNT"]).ToString("F2")} where FCUSTID = {item["fcustid"].ToString()}";
                    DBUtils.Execute(ctx, updSql);
                }
                catch (Exception ex) { }
            }
        }


        /// <summary>
        /// https://vip.kingdee.com/article/337264184725122048?productLineId=1&lang=zh-CN
        /// </summary>
        /// <param name="ctx"></param>
        /// <param name="reportFormId"></param>
        /// <param name="filterFormId"></param>
        /// <param name="dicFilter"></param>
        /// <param name="schemeId"></param>
        /// <returns></returns>
        private DataTable GetReportData(Context ctx, string reportFormId, string filterFormId, Dictionary<string, string> dicFilter, string schemeId)
        {
            try
            {
                ISysReportService sysReporSservice = ServiceFactory.GetSysReportService(ctx);
                IPermissionService permissionService = ServiceFactory.GetPermissionService(ctx);
                var filterMetadata = FormMetaDataCache.GetCachedFilterMetaData(ctx);//加载字段比较条件元数据。
                var reportMetadata = FormMetaDataCache.GetCachedFormMetaData(ctx, reportFormId);//加载对账报表元数据。
                var reportFilterMetadata = FormMetaDataCache.GetCachedFormMetaData(ctx, filterFormId);//加载对账报表过滤条件元数据。
                var reportFilterServiceProvider = reportFilterMetadata.BusinessInfo.GetForm().GetFormServiceProvider();
                var model = new SysReportFilterModel();
                model.SetContext(ctx, reportFilterMetadata.BusinessInfo, reportFilterServiceProvider);
                model.FormId = reportFilterMetadata.BusinessInfo.GetForm().Id;
                model.FilterObject.FilterMetaData = filterMetadata;
                model.InitFieldList(reportMetadata, reportFilterMetadata);
                model.GetSchemeList();
                model.LoadDefaultScheme();//.Load(schemeId);//过滤方案的主键值，可通过该SQL语句查询得到：SELECT * FROM T_BAS_FILTERSCHEME
                var filter = model.GetFilterParameter();
                DynamicObject filterObj = filter.CustomFilter;

                foreach (var item in dicFilter)
                {
                    if (filterObj.Contains(item.Key))
                    {
                        filterObj[item.Key] = item.Value;
                    }
                }

                IRptParams p = new RptParams();
                p.FormId = reportFilterMetadata.BusinessInfo.GetForm().Id;
                p.StartRow = 1;
                p.EndRow = 50000;//StartRow和EndRow是报表数据分页的起始行数和截至行数，一般取所有数据，所以EndRow取int最大值。
                p.FilterParameter = filter;
                p.FilterFieldInfo = model.FilterFieldInfo;
                p.BaseDataTempTable.AddRange(permissionService.GetBaseDataTempTable(ctx, reportMetadata.BusinessInfo.GetForm().Id));

                p.CustomParams.Add("OpenParameter", "");//此参数不能缺少，即使为空也要保留
                p.FilterParameter.GroupbyString = "";

                MoveReportServiceParameter reportServiceParam = new MoveReportServiceParameter(ctx, reportMetadata.BusinessInfo, Guid.NewGuid().ToString(), p);
                IReportData result = sysReporSservice.GetReportData(reportServiceParam);
                ServiceFactory.CloseService(sysReporSservice);
                ServiceFactory.CloseService(permissionService);
                return result.DataSource;
            }
            catch (Exception ex)
            {

            }
            return null;
        }


    }
}
